﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using WFIM.Framework.Collections;
using System.Threading;

namespace WFWS.Core
{
    public class HttpServer
    {
        //Parser receive Stram return ClientRquest then queue it
        //Server manages the ClientRequest queue,
        //so,we need a socket manager to manage the sockets help the server to manipulate the Socket
        //IHttpRequestHandler receive an instance of HttpRequest return a Response
        //Server Send the Response to the server by SocketManager

        HttpListener _listener;
        int _port = 808;
        int _backlog = 50;
        private HttpRequestHandlerFactory _handlerFactory = new HttpRequestHandlerFactory();
        private static HttpServer _server;
        private bool _stopFlag = false;
        Thread _queueThread;

        static HttpServer()
        {
            _server = new HttpServer(808);
        }
        private HttpServer()
            : this(80)
        { }

        private HttpServer(int port)
        {
            _port = port;
            _listener = HttpListener.Create(port, this, ParseAndQueue);
        }

        public static HttpServer Current
        {
            get
            {
                return _server;
            }
        }

        public void Start()
        {
            _listener.Start(_backlog);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="socket"></param>
        internal void ParseAndQueue(Socket socket)
        {
            HttpRequestParser parser = new HttpRequestParser(socket);
            parser.ParseAndQueueRequest();
        }

        /*
        private static void ExecuteQueue(object state)
        {
            while (HttpServer.Current.RequestQueue != null && HttpServer.Current.RequestQueue.Count > 0)
            {
                var request = HttpServer.Current.RequestQueue.Dequeue();
                HttpRequestManager.QueueWorkRequest(request);
                //Here,Need to change 
                //ThreadPool.QueueUserWorkItem(new WaitCallback(ExecuteRequestWorker),request);
            }
        }

        private static void ExecuteRequestWorker(object state)
        {
            var request = state as HttpClientRequest;
            HttpRequestHandlerFactory.Create().Execute(request);
        }
*/
        public void Stop()
        {
            _listener.Stop();
            _queueThread.Suspend();
            _stopFlag = true;
        }
    }
}
